$(function () {

    var args = {
        $dlg: null,
        $form: null
    };

    var interfaces = {
        dataGridUrl: $.contextPath+"device/deviceCheckedInOut!getGrid.action",
        getCategoryList: $.contextPath+"category/category_list",
        getCategoryById: $.contextPath+"category/getCategory",
        getCategoryCommbox: $.contextPath+"category/getCategoryCommbox",
        persistenceCategory: $.contextPath+"category/persistenceCategory",
        deleteCategory: $.contextPath+"category/deleteCategory",
        excelCategory: $.contextPath+"category/excelCategory",
    };

    var jsonPosts = {
        getCategoryById: function (id, onAfter) {
            jqueryUtil.jsonPost(interfaces.getCategoryById, {id: id}, function (rsp) {
                if (onAfter) {
                    onAfter(rsp);
                }
            });
        },
        persistenceCategory: function (param, onAfter) {
            jqueryUtil.jsonPost(interfaces.persistenceCategory, param, function (rsp) {
                if (onAfter) {
                    onAfter(rsp);
                }
            });
        },
        excelCategory: function (param, onAfter) {
            jqueryUtil.jsonPost(interfaces.excelCategory, param, function (rsp) {
                if (onAfter) {
                    onAfter(rsp);
                }
            });
        },
        deleteCategoryById: function (id, onAfter) {
            jqueryUtil.jsonPost(interfaces.deleteCategory, {id: id}, function (rsp) {
                if (onAfter) {
                    onAfter(rsp);
                }
            });
        }
    };

    var events = {
        btnSearch: function () {
            executeQuery()
        },
        executeQuery: function () {
            executeQuery()
        },
        btnAdd: function () {
            addCategory();
        },
        btnExcel:function () {
            excelCategory()
        }
    }

    var selectors = {
        grid: $("#grid"),
        btnSearch: $("#btnSearch"),
        btnAdd: $("#btnAdd"),
        pidCommbox: $("#pid"),
        btnExcel: $("#excel"),
        form: $("#searchForm"),
        form1: $("#from")
    }

    function init() {
        initEvents();
        initGrid();
    }

    function initCommbox(rsp) {
        $("#pid").combobox({
            url: interfaces.getCategoryCommbox,
            valueField: 'id',
            textField: 'text',
            onLoadSuccess: function () {
                if(rsp){
                    $("#form").form("load", rsp);
                }
            }
        })

    }

    function initEvents() {
        selectors.btnSearch.click(events.btnSearch)
        selectors.btnAdd.click(events.btnAdd)
        selectors.btnExcel.click(events.btnExcel)
    }

    function initGrid() {
        selectors.grid.datagrid({
            width: 'auto',
            height: window.innerHeight * 0.9 - 100,
            columns: [[
                {field: 'id', hidden: true},
                {field: 'name', title: '分类名称', width: 100},
                {field: 'type', title: '分类级别', width: 100, formatter: function (value, row, index){
                       if(value ==1) return"一级";
                       else if(value == 2) return "二级";
                    }},
                {
                    field: '-', title: '操作', formatter: function (value, row, index) {
                        var oper = "<a href=\"javascript:void(0)\" onclick=\"editDatagrid(" + row.id + ')">修改</a>';
                        oper += ' <a href="javascript:void(0)" onclick="delDatagrid(' + row.id + ')">删除</a>';
                        return oper;
                    }
                }
            ]],
            singleSelect: true,
            autoRowHeight: true,
            striped: true,
            pagination: true,
            loadMsg: "数据加载中....",
        });

        events.executeQuery();
    }

    this.delDatagrid = function (id) {
        $.messager.confirm('提示信息', '确认删除该分类吗?', function (r) {
            if (r) {
                jsonPosts.deleteCategoryById(id, function (rsp) {
                    if (rsp.success) {
                        $.showMessage(rsp.message)
                        events.executeQuery();
                        args.$dlg.dialog('destroy');
                        args.$dlg = null;
                    } else {
                        $.showMessage(rsp.message)
                    }
                });
            }
        });
    }

    function addCategory() {
        createDlg()
    }

    function createDlg(id) {
        args.$dlg = $('<div />').dialog({
            title: id != null ? "分类修改" : "新增分类",
            href: "category/dlg/categoryDlg.jsp",
            width: 600,
            height: 500,
            buttons: [
                {
                    id: "aSave",
                    text: "保存",
                    handler: function () {
                        var param = $("#form").serializeJSON()
                        jsonPosts.persistenceCategory(param, function (rsp) {
                            if (rsp.success) {
                                $.showMessage(rsp.message)
                                events.executeQuery();
                                args.$dlg.dialog('destroy');
                                args.$dlg = null;
                            } else {
                                $.showMessage(rsp.message)
                            }
                        });
                    }
                },
                {
                    id: "aCancel",
                    text: "关闭",
                    handler: function () {

                        events.executeQuery();
                        args.$dlg.dialog('destroy');
                        args.$dlg = null;
                    }
                }
            ],
            onClose: function () {
                events.executeQuery();
                args.$dlg.dialog('destroy');
                args.$dlg = null;
            },
            onLoad: function () {
                if (id != null) {
                    jsonPosts.getCategoryById(id, function (rsp) {
                        initCommbox(rsp)
                    })
                } else {
                    initCommbox();
                }
            }
        });
    }

    this.editDatagrid = function (id) {
        createDlg(id)
    }

    function excelCategory() {
        var formData = selectors.form.serializeJSON();
        download(interfaces.excelCategory,formData);
    }

    function download(url, data){    // 获得url和data
        var inputs = '';
        $.each(data, function(name, value) {
            inputs+='<input type="hidden" name="'+ name +'" value="'+ value +'" />';
        });
        $('<form action="'+ url +'" method="post">'+inputs+'</form>')
            .appendTo('body').submit().remove();
    };

    function executeQuery() {
        var formData = selectors.form.serializeJSON();
        selectors.grid.datagrid({url: interfaces.getCategoryList, queryParams: formData})
    };

    init()
});
